package com.nsgf.library.ui.page;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.Observer;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.AiRecognitionDetailBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityAlarmEventCompletedBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.photopicker.PhotoPreview;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.photopicker.widget.PhotoAdapter;
import com.nsgf.skjz.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理完成的报警事件详情页面（只读）
 */
public class AlarmEventCompletedActivity extends BaseActivity {

    private CompletedStates mStates;
    private ActivityAlarmEventCompletedBinding mBinding;
    private AccountRequester mAccountRequester;

    private String id = "";
    private List<WorkOrderDetailBean.FileDto> videoList = new ArrayList<>(); // 视频列表

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(CompletedStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_alarm_event_completed, BR.vm, mStates);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityAlarmEventCompletedBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);

        mStates.titleBar.set("报警事件处理");
        id = getIntent().getStringExtra("id");
        // 调用详情接口
        loadAiRecognitionDetail();
        // 设置返回按钮点击事件
        mBinding.titlebar.titleBarBack.setOnClickListener(v -> finish());
    }

    /**
     * 加载AI识别详情
     */
    private void loadAiRecognitionDetail() {
        // 观察接口返回结果
        mAccountRequester.getAiRecognitionDetailResult().observe(this, new Observer<ResponseStatus<AiRecognitionDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<AiRecognitionDetailBean> response) {
                if (response != null) {
                    if (response.getResponseCode() == 200 && response.getData() != null) {
                        // 接口调用成功，处理返回数据
                        AiRecognitionDetailBean detailBean = response.getData();

                        // 绑定数据到布局
                        mBinding.setVmEvent(detailBean);
                        Log.d("AlarmEventCompletedActivity", "AI识别详情加载成功: " + detailBean.getTaskName());

                        // 加载图片和视频列表
                        loadImageAndVideoLists(detailBean);
                    } else {
                        // 接口返回错误
                        Log.e("AlarmEventCompletedActivity", "AI识别详情加载失败: " + response.getMsg());
                        ToastUtils.showLongToast("加载失败: " + response.getMsg());
                    }
                }
            }
        });

        // 调用接口
        mAccountRequester.getAiRecognitionDetail(id);
    }

    /**
     * 加载图片和视频列表
     */
    private void loadImageAndVideoLists(AiRecognitionDetailBean detailBean) {
        // 加载处理后的图片列表（如果有）
        if (detailBean.getHandleImageList() != null && !detailBean.getHandleImageList().isEmpty()) {
            List<WorkOrderDetailBean.FileDto> handleImageFiles = new ArrayList<>();
            for (AiRecognitionDetailBean.FileItem fileItem : detailBean.getHandleImageList()) {
                WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                dto.setFilePath(APIs.BASE_URL_IMG + fileItem.getFilePath());
                dto.setFileName(fileItem.getFileName());
                handleImageFiles.add(dto);
            }
            initImageDisplay(handleImageFiles);
        }

        // 加载处理后的视频列表（如果有）
        if (detailBean.getHandleVideoList() != null && !detailBean.getHandleVideoList().isEmpty()) {
            videoList.clear();
            for (AiRecognitionDetailBean.FileItem fileItem : detailBean.getHandleVideoList()) {
                WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                dto.setFilePath(APIs.BASE_URL_IMG + fileItem.getFilePath());
                dto.setFileName(fileItem.getFileName());
                videoList.add(dto);
            }
            initVideoDisplay();
        }
    }

    /**
     * 初始化图片展示
     */
    private void initImageDisplay(List<WorkOrderDetailBean.FileDto> imageList) {
        if (imageList == null || imageList.isEmpty()) {
            return;
        }

        mBinding.multiPickResultView.init(
                AlarmEventCompletedActivity.this,
                MultiPickResultView.ACTION_ONLY_SHOW, // 只读模式，只显示
                (ArrayList<WorkOrderDetailBean.FileDto>) imageList,
                9,
                0,
                null,
                new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {
                        // 点击图片预览
                        if (imageList != null && position < imageList.size()) {
                            PhotoPreview.builder()
                                    .setPhotos((ArrayList<WorkOrderDetailBean.FileDto>) imageList)
                                    .setAction(MultiPickResultView.ACTION_ONLY_SHOW)
                                    .start(AlarmEventCompletedActivity.this);
                        }
                    }
                }
        );
    }

    /**
     * 初始化视频展示
     */
    private void initVideoDisplay() {
        updateVideoDisplay();
    }

    /**
     * 更新视频显示
     */
    private void updateVideoDisplay() {
        LinearLayout container = mBinding.llVideoContainer;
        container.removeAllViews();

        if (videoList == null || videoList.isEmpty()) {
            return;
        }

        for (int i = 0; i < videoList.size(); i++) {
            WorkOrderDetailBean.FileDto video = videoList.get(i);
            if (video == null || video.getFilePath() == null) {
                continue;
            }

            LinearLayout videoItem = createVideoItem(video, i);
            container.addView(videoItem);
        }
    }

    /**
     * 创建视频项视图
     */
    private LinearLayout createVideoItem(WorkOrderDetailBean.FileDto video, int index) {
        LinearLayout videoItem = new LinearLayout(this);
        videoItem.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(80, 80);
        params.setMargins(0, 0, 10, 0);
        videoItem.setLayoutParams(params);

        // 视频缩略图
        ImageView thumbnail = new ImageView(this);
        thumbnail.setLayoutParams(new LinearLayout.LayoutParams(80, 80));
        thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
        thumbnail.setBackgroundResource(R.drawable.bg_upload_button);

        // 加载视频缩略图
        loadVideoThumbnail(video.getFilePath(), thumbnail);

        // 播放按钮
        TextView playButton = new TextView(this);
        playButton.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
        playButton.setText("▶");
        playButton.setTextColor(0xFFFFFFFF);
        playButton.setTextSize(12);
        playButton.setGravity(android.view.Gravity.CENTER);
        playButton.setBackgroundResource(R.drawable.simple_count_badge_bg);

        RelativeLayout relativeLayout = new RelativeLayout(this);
        relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(80, 80));
        relativeLayout.addView(thumbnail);
        RelativeLayout.LayoutParams playParams = new RelativeLayout.LayoutParams(30, 30);
        playParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        playButton.setLayoutParams(playParams);
        relativeLayout.addView(playButton);

        // 点击播放视频
        final int videoIndex = index;
        relativeLayout.setOnClickListener(v -> {
            // 打开视频播放页面
            Intent intent = new Intent(AlarmEventCompletedActivity.this, VideoPlayerActivity.class);
            intent.putExtra("videoPath", video.getFilePath());
            startActivity(intent);
        });

        videoItem.addView(relativeLayout);
        return videoItem;
    }

    /**
     * 加载视频缩略图
     */
    private void loadVideoThumbnail(String videoPath, ImageView imageView) {
        new Thread(() -> {
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                // 处理 http 和 content:// 两种 URI
                if (videoPath.startsWith("http")) {
                    retriever.setDataSource(videoPath, new java.util.HashMap<>());
                } else if (videoPath.startsWith("content://")) {
                    retriever.setDataSource(this, Uri.parse(videoPath));
                } else {
                    retriever.setDataSource(videoPath);
                }
                Bitmap bitmap = retriever.getFrameAtTime(0);

                runOnUiThread(() -> {
                    if (bitmap != null) {
                        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 80, 80, true);
                        imageView.setImageBitmap(scaledBitmap);
                        if (scaledBitmap != bitmap) {
                            bitmap.recycle();
                        }
                    }
                });
                retriever.release();
            } catch (Exception e) {
                Log.e("AlarmEventCompletedActivity", "加载视频缩略图失败: " + e.getMessage());
            }
        }).start();
    }

    /**
     * States
     */
    public static class CompletedStates extends StateHolder {
        public final State<String> titleBar = new State<>("报警事件处理");
    }

    /**
     * 处理信息数据模型
     */
    public static class ProcessInfo extends BaseObservable {
        private String checkResult; // 检查结果
        private String handler; // 处理人
        private String processingTime; // 处理时间
        private String processingMeasures; // 处理措施

        @Bindable
        public String getCheckResult() {
            return checkResult;
        }

        public void setCheckResult(String checkResult) {
            this.checkResult = checkResult;
            notifyPropertyChanged(BR.checkResult);
        }

        @Bindable
        public String getHandler() {
            return handler;
        }

        public void setHandler(String handler) {
            this.handler = handler;
            notifyPropertyChanged(BR.handler);
        }

        @Bindable
        public String getProcessingTime() {
            return processingTime;
        }

        public void setProcessingTime(String processingTime) {
            this.processingTime = processingTime;
            notifyPropertyChanged(BR.processingTime);
        }

        @Bindable
        public String getProcessingMeasures() {
            return processingMeasures;
        }

        public void setProcessingMeasures(String processingMeasures) {
            this.processingMeasures = processingMeasures;
            notifyPropertyChanged(BR.processingMeasures);
        }
    }
}

